import java.util.ArrayList;


public class GameLogic {
	void makeStep(Field field) {
		makeStepSoldier(field.soldiers);
		makeStepTowers(field.towers);
	}
	
	void makeStepSoldier(ArrayList<Soldier> soldiers) {
		for (int i = 0; i < soldiers.size(); i++) {
			Soldier current = soldiers.get(i);
			current.leftTime--;
			current.x = (current.destination.x - current.depature.x) * (current.leftTime) / 
					current.depature.getDist(current.destination);
			current.y = (current.destination.y - current.depature.y) * (current.leftTime) / 
					current.depature.getDist(current.destination);
			if (current.leftTime == 0) {
				current.destination.peopleCount[current.type] += current.peopleCount;
				soldiers.remove(i);
				i--;
			}
		}
	}
	
	void makeStepTowers(Tower[] towers) {
		for (int i = 0; i < towers.length; i++) {
			Tower current = towers[i];
			if (makeWar(current))
				continue;
			if (current.leftUpgrade >= 0) {
				current.leftUpgrade--;
				if (current.leftUpgrade == -1)
					current.level++;
				else
					continue;
			}
			current.peopleCount[current.type] += current.countBirth();
			if (current.peopleCount[current.type] > current.countMaxPeople()) {
				current.peopleCount[current.type] = Math.max(current.countMaxPeople(),
						current.peopleCount[current.type] - current.countDeath());
			}
		}
	}
	
	boolean countTypeofTower(Tower current) {
		current.type = 0;
		for (int i = 0; i < current.peopleCount.length; i++) {
			if (current.peopleCount[i] > 0) {
				if (current.type > 0)
					return false;
				current.type = i;
			}
		}
		return true;
	}
	
	boolean makeWar(Tower current) {
		for (int iter = 0; iter < current.countWarDeath(); iter++) {
			if (countTypeofTower(current))
				return false;	
			for (int i = 0; i < current.peopleCount.length; i++)
				if (current.peopleCount[i] > 0)
					current.peopleCount[i]--;
		}
		return !countTypeofTower(current);
	}
}
